// Configuration for your app
// https://v2.quasar.dev/quasar-cli-vite/quasar-config-file

//@ts-ignore
import { defineConfig } from '#q-app/wrappers';
import { fileURLToPath } from 'node:url';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';

// 读取 package.json 获取版本号
const packageJson = JSON.parse(readFileSync(join(__dirname, 'package.json'), 'utf-8'));

export default defineConfig((ctx) => {
  return {
    // https://v2.quasar.dev/quasar-cli-vite/prefetch-feature
    // preFetch: true,

    // app boot file (/src/boot)
    // --> boot files are part of "main.js"
    // https://v2.quasar.dev/quasar-cli-vite/boot-files
    boot: ['i18n', 'lccBoot', 'mobileDebug'],

    // https://v2.quasar.dev/quasar-cli-vite/quasar-config-file#css
    css: ['app.css'],

    // https://github.com/quasarframework/quasar/tree/dev/extras
    extras: [
      // 'ionicons-v4',
      // 'mdi-v7',
      // 'fontawesome-v6',
      // 'eva-icons',
      // 'themify',
      // 'line-awesome',
      // 'roboto-font-latin-ext', // this or either 'roboto-font', NEVER both!

      'roboto-font', // optional, you are not bound to it
      'material-icons' // optional, you are not bound to it
    ],

    // Full list of options: https://v2.quasar.dev/quasar-cli-vite/quasar-config-file#build
    build: {
      target: {
        browser: ['es2022', 'firefox115', 'chrome115', 'safari14'],
        node: 'node20'
      },

      typescript: {
        strict: true,
        vueShim: true
        // extendTsConfig (tsConfig) {}
      },

      vueRouterMode: 'hash', // available values: 'hash', 'history'
      // vueRouterBase,
      // vueDevtools,
      // vueOptionsAPI: false,

      // rebuildCache: true, // rebuilds Vite/linter/etc cache on startup

      // publicPath: '/',
      // analyze: true,
      // env: {},
      rawDefine: {
        'import.meta.env.VITE_APP_VERSION': JSON.stringify(packageJson.version)
      },
      // ignorePublicFolder: true,
      // minify: false,
      // polyfillModulePreload: true,
      // distDir

      extendViteConf(viteConf) {
        // 合并Vite配置
        if (viteConf.server) {
          viteConf.server.proxy = {
            '^/api/.*': {
              target: 'http://localhost:7723',
              changeOrigin: false
            }
          };
        }

        // 添加路径别名配置，解决 yvan-lcc-model 导入问题
        if (viteConf.resolve) {
          viteConf.resolve.alias = {
            ...viteConf.resolve.alias
          };
        } else {
          viteConf.resolve = {
            alias: {}
          };
        }
      },
      // viteVuePluginOptions: {},

      vitePlugins: [
        [
          '@intlify/unplugin-vue-i18n/vite',
          {
            // if you want to use Vue I18n Legacy API, you need to set `compositionOnly: false`
            // compositionOnly: false,

            // if you want to use named tokens in your Vue I18n messages, such as 'Hello {name}',
            // you need to set `runtimeOnly: false`
            // runtimeOnly: false,

            ssr: false, // 禁用 SSR

            // you need to set i18n resource including paths !
            include: [fileURLToPath(new URL('./src/i18n', import.meta.url))]
          }
        ]

        // 暂时注释掉 vite-plugin-checker 以避免兼容性问题
        // [
        //   'vite-plugin-checker',
        //   {
        //     vueTsc: {
        //       vueTsc: {
        //         tsconfigPath: './tsconfig.json',
        //       },
        //   },
        //   { server: false },
        // ],
      ]
    },

    // Full list of options: https://v2.quasar.dev/quasar-cli-vite/quasar-config-file#devserver
    devServer: {
      // https: true,
      open: false, // opens browser window automatically
      port: 7600
    },

    // https://v2.quasar.dev/quasar-cli-vite/quasar-config-file#framework
    framework: {
      config: {},

      // iconSet: 'material-icons', // Quasar icon set
      // lang: 'en-US', // Quasar language pack

      // For special cases outside of where the auto-import strategy can have an impact
      // (like functional components as one of the examples),
      // you can manually specify Quasar components/directives to be available everywhere:
      //
      // components: [],
      // directives: [],

      // Quasar plugins
      plugins: ['Notify', 'Loading', 'Dialog', 'AppFullscreen', 'Notify']
    },

    // animations: 'all', // --- includes all animations
    // https://v2.quasar.dev/options/animations
    animations: [],

    // https://v2.quasar.dev/quasar-cli-vite/quasar-config-file#sourcefiles
    // sourceFiles: {
    //   rootComponent: 'src/App.vue',
    //   router: 'src/router/index',
    //   store: 'src/stores/index',
    //   pwaRegisterServiceWorker: 'src-pwa/register-service-worker',
    //   pwaManifestFile: 'src-pwa/manifest.json',
    //   electronMain: 'src-electron/electron-main',
    //   electronPreload: 'src-electron/electron-preload'
    // },

    // https://v2.quasar.dev/quasar-cli-vite/developing-pwa/configuring-pwa
    pwa: {
      workboxMode: 'GenerateSW',
      injectPwaMetaTags: true,
      swFilename: 'sw.js',
      manifestFilename: 'manifest.json',
      useCredentialsForManifestTag: false,
      // useFilenameHashes: true,
      extendGenerateSWOptions(cfg) {
        // 确保Service Worker正确注册
        cfg.skipWaiting = true;
        cfg.clientsClaim = true;

        // 配置离线缓存策略
        cfg.runtimeCaching = [
          // 添加对HTTP API的支持
          {
            urlPattern: /^http:\/\/180\.100\.199\.56:8006\/.*/i,
            handler: 'NetworkFirst',
            options: {
              cacheName: 'api-cache',
              expiration: {
                maxEntries: 100,
                maxAgeSeconds: 5 * 60 // 5分钟
              },
              networkTimeoutSeconds: 10,
              cacheableResponse: {
                statuses: [0, 200, 401, 403, 404, 500]
              }
            }
          },
          // 支持所有192.*开头的IP地址
          {
            urlPattern: /^http:\/\/192\.\d+\.\d+\.\d+:\d+\/.*/i,
            handler: 'NetworkFirst',
            options: {
              cacheName: '192-network-cache',
              expiration: {
                maxEntries: 100,
                maxAgeSeconds: 5 * 60 // 5分钟
              },
              networkTimeoutSeconds: 10,
              cacheableResponse: {
                statuses: [0, 200, 401, 403, 404, 500]
              }
            }
          },
          // 支持所有10.*开头的IP地址
          {
            urlPattern: /^http:\/\/10\.\d+\.\d+\.\d+:\d+\/.*/i,
            handler: 'NetworkFirst',
            options: {
              cacheName: '10-network-cache',
              expiration: {
                maxEntries: 100,
                maxAgeSeconds: 5 * 60 // 5分钟
              },
              networkTimeoutSeconds: 10,
              cacheableResponse: {
                statuses: [0, 200, 401, 403, 404, 500]
              }
            }
          },
          // 代理路由配置
          {
            urlPattern: /^\/api\/external\/.*/i,
            handler: 'NetworkFirst',
            options: {
              cacheName: 'proxy-external-cache',
              expiration: {
                maxEntries: 50,
                maxAgeSeconds: 5 * 60
              },
              networkTimeoutSeconds: 10,
              cacheableResponse: {
                statuses: [0, 200, 401, 403, 404, 500]
              }
            }
          },
          {
            urlPattern: /^\/api\/192\/.*/i,
            handler: 'NetworkFirst',
            options: {
              cacheName: 'proxy-192-cache',
              expiration: {
                maxEntries: 50,
                maxAgeSeconds: 5 * 60
              },
              networkTimeoutSeconds: 10,
              cacheableResponse: {
                statuses: [0, 200, 401, 403, 404, 500]
              }
            }
          },
          {
            urlPattern: /^\/api\/10\/.*/i,
            handler: 'NetworkFirst',
            options: {
              cacheName: 'proxy-10-cache',
              expiration: {
                maxEntries: 50,
                maxAgeSeconds: 5 * 60
              },
              networkTimeoutSeconds: 10,
              cacheableResponse: {
                statuses: [0, 200, 401, 403, 404, 500]
              }
            }
          },
          {
            urlPattern: /^https:\/\/fonts\.googleapis\.com\/.*/i,
            handler: 'CacheFirst',
            options: {
              cacheName: 'google-fonts-cache',
              expiration: {
                maxEntries: 10,
                maxAgeSeconds: 60 * 60 * 24 * 365 // 1年
              },
              cacheableResponse: {
                statuses: [0, 200]
              }
            }
          },
          {
            urlPattern: /^https:\/\/fonts\.gstatic\.com\/.*/i,
            handler: 'CacheFirst',
            options: {
              cacheName: 'gstatic-fonts-cache',
              expiration: {
                maxEntries: 10,
                maxAgeSeconds: 60 * 60 * 24 * 365 // 1年
              },
              cacheableResponse: {
                statuses: [0, 200]
              }
            }
          },
          {
            urlPattern: /\.(?:eot|otf|ttc|ttf|woff|woff2|font.css)$/i,
            handler: 'StaleWhileRevalidate',
            options: {
              cacheName: 'static-font-assets',
              expiration: {
                maxEntries: 4,
                maxAgeSeconds: 7 * 24 * 60 * 60 // 7天
              },
              cacheableResponse: {
                statuses: [0, 200]
              }
            }
          },
          {
            urlPattern: /\.(?:jpg|jpeg|gif|png|svg|ico|webp)$/i,
            handler: 'StaleWhileRevalidate',
            options: {
              cacheName: 'static-image-assets',
              expiration: {
                maxEntries: 64,
                maxAgeSeconds: 24 * 60 * 60 // 24小时
              },
              cacheableResponse: {
                statuses: [0, 200]
              }
            }
          },
          {
            urlPattern: /.*/i,
            handler: 'NetworkFirst',
            options: {
              cacheName: 'others',
              expiration: {
                maxEntries: 32,
                maxAgeSeconds: 24 * 60 * 60 // 24小时
              },
              networkTimeoutSeconds: 10,
              cacheableResponse: {
                statuses: [0, 200]
              }
            }
          }
        ];
      },
      extendManifestJson(json) {
        // 确保manifest.json包含所有必需的字段
        json.name = 'GalaxisLCC';
        json.short_name = 'GalaxisLCC';
        json.description = 'Galaxis LCC 世界模型系统';
        json.start_url = '/';
        json.scope = '/';
        json.display = 'standalone';
        json.background_color = '#ffffff';
        json.theme_color = '#027be3';
        json.orientation = 'portrait-primary';
        json.prefer_related_applications = false;
        json.categories = ['productivity', 'utilities'];
        json.lang = 'zh-CN';
        json.dir = 'ltr'
        ;(json as any).display_override = ['standalone', 'minimal-ui']
        ;(json as any).launch_handler = {
          'client_mode': 'focus-existing'
        }
        ;(json as any).permissions = ['http://*', 'https://*'];
      }
      // extendInjectManifestOptions (cfg) {},
      // extendPWACustomSWConf (esbuildConf) {}
      // extendPwaWebpackConf (esbuildConf) {}
    },

    // Full list of options: https://v2.quasar.dev/quasar-cli-vite/developing-cordova-apps/configuring-cordova
    cordova: {
      // noIosLegacyBuildFlag: true, // uncomment only if you know what you are doing
    },

    // Full list of options: https://v2.quasar.dev/quasar-cli-vite/developing-capacitor-apps/configuring-capacitor
    // capacitor: {
    //   hideSplashscreen: true,
    // },

    // Full list of options: https://v2.quasar.dev/quasar-cli-vite/developing-electron-apps/configuring-electron
    electron: {
      // extendElectronMainConf (esbuildConf)
      // extendElectronPreloadConf (esbuildConf)

      inspectPort: 5858,

      bundler: 'packager', // 'packager' or 'builder'

      packager: {
        // https://github.com/electron-userland/electron-packager/blob/master/docs/api.md#options

        // OS X / Mac App Store
        // appBundleId: '',
        // appCategoryType: '',
        // osxSign: '',
        // protocol: 'myapp://path',

        // Windows only
        // win32metadata: { ... }
      },

      builder: {
        // https://www.electron.build/configuration/configuration

        appId: 'lcc-frontend'
      }
    },

    // Full list of options: https://v2.quasar.dev/quasar-cli-vite/developing-browser-extensions/configuring-bex
    bex: {
      // extendBexScriptsConf (esbuildConf) {},
      // extendBexManifestJson (json) {},

      /**
       * The list of extra scripts (js/ts) not in your bex manifest that you want to
       * compile and use in your browser extension. Maybe dynamic use them?
       *
       * Each entry in the list should be a relative filename to /src-bex/
       *
       * @example [ 'my-script.ts', 'sub-folder/my-other-script.js' ]
       */
      extraScripts: []
    }
  };
});
